//
//  HelpModelObject.m
//  project
//
//  Created by 黄建华 on 2017/9/26.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNEveryDayModelHelp.h"
#define BLT_InfoDelayTime 0.5 // 蓝牙通信间隔 避免造成堵塞.

@implementation SNEveryDayModelHelp
DEF_SINGLETON(SNEveryDayModelHelp)

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    
    return self;
}

// 取出今天的数据模型
+ (EveryDayModel *)getModelFromDBWithToday {
    EveryDayModel *model = [SNEveryDayModelHelp getModelFromDBWithDate:[NSDate date]];
    
    if (model) {
        return model;
    } else {
        model = [[EveryDayModel alloc] init];
        return model;
    }
}

+ (EveryDayModel *)getModelFromDBWithYes {
    NSDate        *yes   = [[NSDate date]dateAfterDay:-1];
    EveryDayModel *model = [SNEveryDayModelHelp getModelFromDBWithDate:yes];
    
    if (model) {
        return model;
    } else {
        model = [[EveryDayModel alloc] init];
        return model;
    }
}

+ (SNUserInfoModel *)getUserModel {
    NSString *userID = [KK_LastUser getObjectValue];
    
    if (!userID) {
        userID = @"GetFit3";
    }
    SNUserInfoModel *model = [SNUserInfoModel getUserInfoFromDBWithUserID:userID];
    
    return model;
}

// 根据日期取出模型。
+ (EveryDayModel *)getModelFromDBWithDate:(NSDate *)date {
    NSString *dateString = [date dateToString];
    NSString *where      = [NSString stringWithFormat:@"dateString = '%@' and user_id = '%@' ",
                            [dateString componentsSeparatedByString:@" "][0], [KK_LastUser getObjectValue]];
    
    EveryDayModel *model = [EveryDayModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        // 没有就进行完全创建.
        model = [SNEveryDayModelHelp pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    
    return model;
}

#pragma getModelWithOutUpdateFromLocalDB
+ (NSArray *)getModelWithOutUpdateFromLocalDBStep {
    NSString *sy             = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *st             = [[[NSDate date] dateAfterDay:0] dateToDayString];
    NSString *lastDateString = [LASTUPDATESTEP getObjectValue];
    
    if (!lastDateString) {
        lastDateString = st;
        [LASTUPDATESTEP setObjectValue:lastDateString];
    }
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString >'%@' and step >0", SN_USER.user_id, lastDateString];
    NSArray  *array = [SportModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    return array;
}

+ (NSArray *)getModelWithOutUpdateFromLocalDBSleep {
    NSString *sy             = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *st             = [[[NSDate date] dateAfterDay:0] dateToDayString];
    NSString *lastDateString = [LASTUPDATESLEEP getObjectValue];
    
    if (!lastDateString) {
        lastDateString = st;
        [LASTUPDATESLEEP setObjectValue:lastDateString];
    }
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString > '%@' and durations >0", SN_USER.user_id, lastDateString];
    NSArray  *array = [SleepModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    return array;
}

+ (NSArray *)getModelWithOutUpdateFromLocalDBHeart {
    NSString *sy             = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *st             = [[[NSDate date] dateAfterDay:0] dateToDayString];
    NSString *lastDateString = [LASTUPDATEHEART getObjectValue];
    
    if (!lastDateString) {
        lastDateString = st;
        [LASTUPDATEHEART setObjectValue:lastDateString];
    }
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString > '%@' and heartMin >0", SN_USER.user_id, lastDateString];
    NSArray  *array = [HeartModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    return array;
}

+ (NSArray *)getModelWithOutUpdateFromLocalDBOx {
    NSString *sy             = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *st             = [[[NSDate date] dateAfterDay:0] dateToDayString];
    NSString *lastDateString = [LASTUPDATEOX getObjectValue];
    
    if (!lastDateString) {
        lastDateString = st;
        [LASTUPDATEOX setObjectValue:lastDateString];
    }
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString > '%@' and oxMin >0", SN_USER.user_id, lastDateString];
    NSArray  *array = [OxModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    return array;
}

+ (NSArray *)getModelWithOutUpdateFromLocalDBBp {
    NSString *sy             = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *st             = [[[NSDate date] dateAfterDay:0] dateToDayString];
    NSString *lastDateString = [LASTUPDATEBP getObjectValue];
    
    if (!lastDateString) {
        lastDateString = st;
        [LASTUPDATEBP setObjectValue:lastDateString];
    }
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString > '%@' and SBPAve >0", SN_USER.user_id, lastDateString];
    NSArray  *array = [BpModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    
    return array;
}

// 根据选中日期返回周所有模型
+ (NSArray *)getWeekModelFromDBWithDate:(NSDate *)date {
    NSDate *newDate = date;
    
    if (newDate == nil) {
        newDate = [NSDate date];
    }
    double     interval   = 0;
    NSDate     *beginDate = nil;
    NSDate     *endDate   = nil;
    NSCalendar *calendar  = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//设定周一为周首日
    BOOL           ok;
    NSCalendarUnit unit = NSWeekCalendarUnit;
    
    ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    NSString *begingString = [beginDate dateToDayString];
    NSString *endString    = [endDate dateToDayString];
    NSString *nowString    = [[NSDate date] dateToDayString];
    NSString *where        = @"";
    BOOL     sameWeek      = [SNEveryDayModelHelp isSameWeek:date withOtherWeek:[NSDate date] withTyoe:0];
    if (sameWeek) {
        where = [NSString stringWithFormat:@"dateString >= '%@' and dateString <= '%@' ",
                 begingString, nowString];
    } else {
        where = [NSString stringWithFormat:@"dateString >= '%@' and dateString <= '%@' ",
                 begingString, endString];
    }
    
    NSArray *array = [EveryDayModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    return array;
}

// 根据选中日期返回月所有模型
+ (NSArray *)getMonthModelFromDBWithDate:(NSDate *)date {
    NSDate *newDate = date;
    
    if (newDate == nil) {
        newDate = [NSDate date];
    }
    double     interval   = 0;
    NSDate     *beginDate = nil;
    NSDate     *endDate   = nil;
    NSCalendar *calendar  = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//设定周一为周首日
    BOOL           ok;
    NSCalendarUnit unit = NSMonthCalendarUnit;
    
    ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    NSString *begingString = [beginDate dateToDayString];
    NSString *endString    = [endDate dateToDayString];
    NSString *nowString    = [[NSDate date] dateToDayString];
    NSString *where        = @"";
    BOOL     sameWeek      = [SNEveryDayModelHelp isSameWeek:date withOtherWeek:[NSDate date] withTyoe:1];
    if (sameWeek) {
        where = [NSString stringWithFormat:@"dateString >= '%@' and dateString <= '%@' ",
                 begingString, nowString];
    } else {
        where = [NSString stringWithFormat:@"dateString >= '%@' and dateString <= '%@' ",
                 begingString, endString];
    }
    
    NSArray *array = [EveryDayModel searchWithWhere:where orderBy:@"dateString" offset:-1 count:0];
    return array;
}

+ (BOOL)isSameWeek:(NSDate *)date1 withOtherWeek:(NSDate *)date2 withTyoe:(NSInteger)type {
    BOOL same = NO;
    
    if (type == 0) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger  week1     = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date1];
        NSInteger  week2     = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date2];
        if (week1 == week2) {
            same = YES;
        }
    } else if (type == 1) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger  month1    = [calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:date1];
        NSInteger  month2    = [calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:date2];
        if (month1 == month2) {
            same = YES;
        }
    } else if (type == 2) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger  year1     = [calendar ordinalityOfUnit:NSCalendarUnitYear inUnit:NSCalendarUnitYear forDate:date1];
        NSInteger  year2     = [calendar ordinalityOfUnit:NSCalendarUnitYear inUnit:NSCalendarUnitYear forDate:date2];
        if (year1 == year2) {
            same = YES;
        }
    }
    return same;
}

// 保存空模型到数据库.
+ (EveryDayModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    EveryDayModel *model = [EveryDayModel simpleInitWithDate:date];
    
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    
    [model saveToDB];
    
    return model;
}

// 移除头像
- (void)removeUserHeadImage {
    NSString      *filePath    = [self headImagePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager removeItemAtPath:filePath error:nil];
}

// 缓存用户头像到本地.
- (void)saveHeadImageToFileCacheWithImage:(UIImage *)image {
    UIImage  *scaleImage = [image imageScaleToSize:CGSizeMake(200.0, 200.0)];
    NSString *filePath   = [self headImagePath];
    NSData   *data       = UIImageJPEGRepresentation(scaleImage, 1.0);
    
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
}

// 获取用户头像.
- (UIImage *)localHeadImage {
    NSString *filePath = [self headImagePath];
    
    if ([self completePathDetermineIsThere:filePath]) {
        return [UIImage imageWithPath:filePath];
    } else {
        // 默认头像图片
        return UIImageNamed(@"loginhead");
    }
}

- (NSString *)headImagePath {
    NSString *filePath = [[XYSandbox libCachePath] stringByAppendingPathComponent:KK_HeadImage];
    
    return filePath;
}

- (void)startUpdateUserInfo {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartUpdateUserInfo) object:nil];
    [self performSelector:@selector(delayStartUpdateUserInfo) withObject:nil afterDelay:0.2];
}

- (void)delayStartUpdateUserInfo {
    [KK_BLESend sendUserInfoSettingWithBlock:^(id object, KKBLEAcceptType type) {
    }];
}

- (void)startDrinkWater {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartDrinkWater) object:nil];
    [self performSelector:@selector(delayStartDrinkWater) withObject:nil afterDelay:0.2];
}

- (void)delayStartDrinkWater {
    [KK_BLESend sendDrinkWithUpdateBlock:^(id object, KKBLEAcceptType type) {
    }];
}

- (void)startsedentary {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartsedentary) object:nil];
    [self performSelector:@selector(delayStartsedentary) withObject:nil afterDelay:0.2];
}

- (void)delayStartsedentary {
    [KK_BLESend sendSedentaryRemindWithUpdateBlock:^(id object, KKBLEAcceptType type) {
    }];
}

// 设置闹钟
- (void)startSetAlarmClock {
    _alarmCount = 5;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartSetAlarmClock) object:nil];
    [self performSelector:@selector(delayStartSetAlarmClock) withObject:nil afterDelay:0.2];
}

- (void)delayStartSetAlarmClock {
    _alarmCount = 0;
    [self sendClockSetting];
}

- (void)sendClockSetting {
    if (KK_BLEConnect.isConnected) {
        if (5 > _alarmCount) {
            SNAlarmModel *model = SN_USER.alarmArray[_alarmCount];
            [KK_BLESend sendSetDeviceAlarmClock_KK:model withUpdateBlock:^(id object, KKBLEAcceptType type) {
                if (type == KKBLEAcceptTypeAlarmClock) {
                    NSLog(@"闹钟:%d>>>>>同步成功>>>>>", _alarmCount);
                    _alarmCount++;
                    [self performSelector:@selector(sendClockSetting)
                               withObject:nil
                               afterDelay:BLT_InfoDelayTime];
                }
            }];
        }
    }
}

// 设置日程
- (void)startSetCalendar {
    _scheduleCount = 5;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartSetCalendar) object:nil];
    [self performSelector:@selector(delayStartSetCalendar) withObject:nil afterDelay:0.2];
}

- (void)delayStartSetCalendar {
    _scheduleCount = 0;
    [self sendCalendarSetting];
}

// 设置日程提醒
- (void)sendCalendarSetting {
    if (KK_BLEConnect.isConnected) {
        if (5 > _scheduleCount) {
            SNcalendarModel *model = SN_USER.calendarArray[_scheduleCount];
            [KK_BLESend sendSetDeviceCalendarModel:model withUpdateBlock:^(id object, KKBLEAcceptType type) {
                if (type == KKBLEAcceptTypeCalendar) {
                    NSLog(@"日程:%d>>>>>同步成功>>>>>", _scheduleCount);
                    _scheduleCount++;
                    [self performSelector:@selector(sendCalendarSetting)
                               withObject:nil
                               afterDelay:BLT_InfoDelayTime];
                }
            }];
        }
    }
}

// 发送低电 抬腕 防丢 心率检测 翻腕切屏 消息推送 电话 短信
- (void)startUpdateSettingOther {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartUpdateSettingOther) object:nil];
    [self performSelector:@selector(delayStartUpdateSettingOther) withObject:nil afterDelay:0.2];
}

- (void)delayStartUpdateSettingOther {
    [KK_BLESend sendSetLowElecWithUpdateBlock:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeOther) {
        }
    }];
}

- (void)startUpdateSettingOther1 {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayStartUpdateSettingOther1) object:nil];
    [self performSelector:@selector(delayStartUpdateSettingOther1) withObject:nil afterDelay:0.2];
}

- (void)delayStartUpdateSettingOther1 {
    [KK_BLESend sendSetPushNoticeWithUpdateBlock:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeNotify) {
        }
    }];
}

// 天气 等其他扩展协议
- (void)startUpdateSettingOther2 {
}

@end

